/*
 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import 'dart:convert';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_huawei_login/webview.dart';
import 'login_view.dart';
import 'package:fluttertoast/fluttertoast.dart';

void main() {
  runApp(const MaterialApp(home: MyHome()));
}

class MyHome extends StatelessWidget {
  const MyHome({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: LoginExample(),
    );
  }
}

class LoginExample extends StatefulWidget {
  const LoginExample({Key? key}) : super(key: key);

  @override
  State<LoginExample> createState() => _LoginExampleState();
}

class _LoginExampleState extends State<LoginExample> {
  String userInfo = '';
  String phoneNumber = '';
  bool agreement = false;
  LoginViewController? _controller;

  var contextRef;

  void _onCustomOhosViewCreated(LoginViewController controller) {
    _controller = controller;
    _controller?.customDataStream.listen((data) {
      //接收到来自OHOS端的数据
      final result = jsonDecode(data);
      setState(() {
        switch (result['method']) {
          case 'getMessageFromOhosView':
            userInfo = result['data'];
            break;
          case 'quickLoginAnonymousPhone':
            phoneNumber = result['data'];
            break;
          case '1005300001':
            _showDialog();
            break;
        }
      });
    });
  }

  Widget _buildFlutterViewTop(BuildContext context) {
    return Expanded(
      child: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.max,
            children: [
              Expanded(child: Container()),
              const Image(
                image: AssetImage('images/icon.png'),
                width: 80,
              ),
              Expanded(child: Container()),
              Text(
                phoneNumber,
                style: const TextStyle(
                    color: Colors.black,
                    fontSize: 40,
                    fontWeight: FontWeight.w900),
              ),
              const Text(
                '华为账号绑定号码',
                style: TextStyle(color: Colors.grey),
              ),
              Expanded(child: Container()),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildLoginOhosView(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(left: 20, top: 20, right: 20),
      height: 40,
      color: Colors.blueAccent.withAlpha(60),
      child: HuaweiLoginView(_onCustomOhosViewCreated),
    );
  }

  Widget _buildOtherLogin(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 10, left: 20, right: 20),
      width: double.infinity,
      height: 40,
      child: TextButton(
        style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(Color(0xFFD6D6D6)),
            foregroundColor: MaterialStateProperty.all(Colors.black),
            shape: MaterialStatePropertyAll(RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(50),
            ))),
        onPressed: () {
          Fluttertoast.showToast(msg: '其他方式登录');
        },
        child: const Text(
          "其他方式登录",
          style: TextStyle(
              color: Colors.black, fontSize: 16, fontWeight: FontWeight.w700),
        ),
      ),
    );
  }

  void openWeb() {
    Navigator.push(
        contextRef,
        MaterialPageRoute(
            builder: (context) => const WebPage(title: "https://www.baidu.com")));
  }

  void _showDialog() {
    showDialog(
      context: contextRef,
      barrierDismissible: false,
      builder: (context) {
        return WillPopScope(
          onWillPop: () async => false,
          child: AlertDialog(
            title: const Text('用户协议与隐私条款',
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 24,
                    fontWeight: FontWeight.w900)),
            content:GestureDetector(
              child: Container(
                child: Wrap(
                  children: [
                    RichText(
                      text: TextSpan(
                        style: TextStyle(color: Colors.white),
                        children: <InlineSpan>[
                          const TextSpan(
                            text: '已阅读并同意',
                            style: TextStyle(color: Colors.grey),
                          ),
                          TextSpan(
                            text: '《xxxx11122用户协议》',
                            style: const TextStyle(color: Colors.black),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {

                                Navigator.of(context).push(MaterialPageRoute(
                                    builder: (context) => const WebPage(
                                      title: "",
                                    )));

                                Fluttertoast.showToast(msg: '《xxxx1用户协议》');
                              },
                          ),
                          TextSpan(
                            text: '《xxxx隐私协议》',
                            style: const TextStyle(color: Colors.black),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Fluttertoast.showToast(msg: '《xxxx隐私协议》');
                              },
                          ),
                          const TextSpan(
                            text: '和',
                            style: TextStyle(color: Colors.grey),
                          ),
                          TextSpan(
                            text: '《华为账号用户认证协议》',
                            style: const TextStyle(color: Colors.black),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Fluttertoast.showToast(msg: '《华为账号用户认证协议》');
                              },
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
            actions: [
              TextButton(
                child: Text('cancel'),
                onPressed: () {
                  Navigator.pop(contextRef);
                },
              ),
              TextButton(
                child: Text('Go to New Page'),
                onPressed: () {
                  Navigator.of(contextRef).push(MaterialPageRoute(
                    builder: (context) =>
                        const WebPage(title: "https://www.baidu.com"),
                  ));
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildFlutterView(BuildContext context) {
    return Expanded(
      child: Stack(
        alignment: AlignmentDirectional.bottomCenter,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              Row(
                children: [
                  Checkbox(
                    shape: const CircleBorder(),
                    value: agreement, // 初始状态为选中
                    activeColor: Colors.red, // 选中时的颜色
                    onChanged: (v) {
                      setState(() {
                        agreement = v!;
                        _controller?.setAgreementStatus(agreement);
                      });
                    },
                  ),
                  Expanded(
                    child: GestureDetector(
                      child: Wrap(
                        children: [
                          RichText(
                            text: TextSpan(
                              style: TextStyle(color: Colors.white),
                              children: <InlineSpan>[
                                const TextSpan(
                                  text: '已阅读并同意',
                                  style: TextStyle(color: Colors.grey),
                                ),
                                TextSpan(
                                  text: '《xxxx用户协议》',
                                  style: const TextStyle(color: Colors.black),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                              const WebPage(
                                                title: "",
                                              )));

                                      Fluttertoast.showToast(
                                          msg: '《xxxx用户协议》');
                                    },
                                ),
                                TextSpan(
                                  text: '《xxxx隐私协议》',
                                  style: const TextStyle(color: Colors.black),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      Fluttertoast.showToast(msg: '《xxxx隐私协议》');
                                    },
                                ),
                                const TextSpan(
                                  text: '和',
                                  style: TextStyle(color: Colors.grey),
                                ),
                                TextSpan(
                                  text: '《华为账号用户认证协议》',
                                  style: const TextStyle(color: Colors.black),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      Fluttertoast.showToast(
                                          msg: '《华为账号用户认证协议》');
                                    },
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
              const SizedBox(height: 50)
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    contextRef = context;
    return Column(
      children: [
        _buildFlutterViewTop(context),
        _buildLoginOhosView(context),
        _buildOtherLogin(context),
        _buildFlutterView(context),
      ],
    );
  }
}